package com.uwantsoft.business.infrastructure.repository;

import com.uwantsoft.business.facade.dto.user.DriverOverviewQueryCondition;
import com.uwantsoft.business.infrastructure.repository.querier.DriverOverviewQuerier;
import com.uwantsoft.business.service.domain.addresses.FavoriteAddress;
import com.uwantsoft.business.service.domain.user.Driver;
import com.uwantsoft.business.service.domain.user.LicensePlate;
import com.uwantsoft.business.service.infrastructure.DriverRepository;
import com.uwantsoft.util.HibernateEntityRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author LeiPeichen.
 */
@SuppressWarnings("unchecked")
@Repository(value = "hibernateDriverRepository")
public class HibernateDriverRepository extends HibernateEntityRepository implements DriverRepository{

    @Override
    public Driver findByPhoneNumber(String phoneNumber) {
        List<Driver> drivers = (List<Driver>)getHibernateTemplate().find("from Driver d where d.active=true and d.username=?",phoneNumber);
        return drivers.isEmpty() ? null : drivers.get(0);
    }

    @Override
    public List<FavoriteAddress> findFavoriteAddresses(Driver driver) {
        return (List<FavoriteAddress>)getHibernateTemplate().find("from FavoriteAddress f where f.driver = ?",driver);
    }

    @Override
    public List<LicensePlate> findLicensePlates(Driver driver) {
        return (List<LicensePlate>)getHibernateTemplate().find("from LicensePlate l where l.driver=?",driver);
    }

    @Override
    public LicensePlate findLicensePlate(String licensePlateNumber) {
        List<LicensePlate> licensePlates = (List<LicensePlate>)getHibernateTemplate().find("from LicensePlate l where l.licensePlateNumber = ?",licensePlateNumber);
        return licensePlates.isEmpty() ? null : licensePlates.get(0);
    }

    @Override
    public LicensePlate findPriorityLicensePlate() {
        List<LicensePlate> priorityLicensePlates = (List <LicensePlate>)getHibernateTemplate().find("from LicensePlate l where l.priority = true");
        return priorityLicensePlates.isEmpty() ? null : priorityLicensePlates.get(0);
    }

    @Override
    public List<Driver> findDrivers(DriverOverviewQueryCondition condition) {
        DriverOverviewQuerier querier = new DriverOverviewQuerier(getHibernateTemplate(),condition);
        return querier.getResults();
    }

    @Override
    public int findDriverTotalAmount(DriverOverviewQueryCondition condition) {
        DriverOverviewQuerier querier = new DriverOverviewQuerier(getHibernateTemplate(),condition);
        return querier.getAmount();
    }
}
